package com.bozer.springsecuritydemo.filter;

import com.bozer.springsecuritydemo.constant.Constants;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.MediaType;
import org.springframework.security.authentication.AuthenticationServiceException;
import org.springframework.web.filter.GenericFilterBean;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

/**
 * 图片验证码过滤器
 */
public class VerifyCodeFilter extends GenericFilterBean {

    private ObjectMapper objectMapper;

    public VerifyCodeFilter(ObjectMapper objectMapper) {
        this.objectMapper = objectMapper;
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
        if ("/login".equals(httpServletRequest.getServletPath())) {
            String code = request.getParameter("code");
            if (code==null||!code.equalsIgnoreCase((String) httpServletRequest.getSession().getAttribute(Constants.VERIFY_CODE_NAME))) {
//            throw new AuthenticationServiceException("验证码输入有误");
                response.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);
                objectMapper.writeValue(response.getWriter(), "验证码输入有误");
                return;
            }
        }
        chain.doFilter(request, response);
    }

}
